package com.zt.rongda.ad.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.rongda.ad.inter.AdDesignMapper;
import com.zt.rongda.ad.model.AdDesign;
import com.zt.rongda.constant.BusConstant;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class AdDesignService extends BaseService {

    @Autowired
    private AdDesignMapper adDesignMapper;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from AD_DESIGN where 1=1 ");
        if (StringUtil.isNotEmpty(reqBean.getInfo("status"))) {
            sqlBuilder.addWhere("STATUS", reqBean.getInfo("status"));
        }
        if (StringUtil.isNotEmpty(reqBean.getInfo("adName"))) {
            sqlBuilder.addWhereLike2("AD_NAME", reqBean.getInfo("adName"));
        }
        if (StringUtil.isNotEmpty(reqBean.getInfo("customerId"))) {
            sqlBuilder.addWhere("CUSTOMER_ID", reqBean.getInfo("customerId"));
        }

        sqlBuilder.orderBy(" ORDER BY MAKE_TIME DESC ");
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONArray getCustomerAds(String customerId, ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from AD_DESIGN where CUSTOMER_ID = '" + customerId + "' ");
        sqlBuilder.addWhere("STATUS", BusConstant.AddesignStatus.FINISHED);

        if (StringUtil.isNotEmpty(reqBean.getInfo("adName"))) {
            sqlBuilder.addWhere("AD_NAME", reqBean.getInfo("customerId"));
            sqlBuilder.appendSql(" and ( instr('" + reqBean.getInfo("adName") + "', AD_NAME) > 0 or AD_NAME like '%"
                    + reqBean.getInfo("adName") + "%')");
        }
        sqlBuilder.orderBy(" order by MAKE_TIME DESC ");
        return query(sqlBuilder);
    }

    /**
     * 新增
     * 
     * @param adDesign
     */
    public void add(AdDesign adDesign, JSONArray files) {
        adDesign.setAdId(stringId());// 手动设置Id
        adDesign.setMakeTime(new Date());
        adDesign.setModifyTime(adDesign.getMakeTime());
        adDesignMapper.insert(adDesign);
    }

    /**
     * 修改
     * 
     * @param adDesign
     */
    public void update(AdDesign adDesign, JSONArray files) {
        String adId = adDesign.getAdId();
        if (StringUtil.isEmpty(adId)) {
            throw new BusinessException("获取主键失败");
        }

        adDesign.setModifyTime(new Date());
        adDesignMapper.updateByPrimaryKeySelective(adDesign);

    }

    /**
     * 删除
     * 
     * @param adId
     */
    public void delete(String adId) {
        if (StringUtil.isEmpty(adId)) {
            throw new BusinessException("获取主键失败");
        }
        adDesignMapper.deleteByPrimaryKey(adId);
    }

    /**
     * 下载附件
     * @param reqBean
     * @param request
     * @param response
     */
    public void downloadFile(ReqBean reqBean, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String url = reqBean.getInfo("filePath");
        String adId = reqBean.getInfo("adId");
        String filePath = BusConstant.ATTACHMENT_PATH + "/" + url;
        response.reset();
        response.setContentType("text/html;charset=utf-8");
        String fileName = URLEncoder.encode("样刊设计-" + adId + ".png", "UTF-8");
        // String fileName = url.substring(url.lastIndexOf("/") + 1,
        // url.length());
        response.addHeader("Content-Disposition", "attachment; filename="
                + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        byte[] buff = new byte[2048];

        try {
            bis = new BufferedInputStream(new FileInputStream(filePath));
            bos = new BufferedOutputStream(response.getOutputStream());
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}